package com.bdth.controller;

import com.bdth.model.*;
import com.bdth.service.IDepartmentService;
import com.bdth.service.IEnclosureService;
import com.bdth.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author: 徐斌
 * @Date: 2018-04-18 11:48
 */
@Controller
@RequestMapping("/area")
public class AreaController extends BaseController {

	@Autowired
	private IEnclosureService enclosureService;

	@Autowired
	private IDepartmentService departmentService;


	/**
	 * 查看marker页面
	 *
	 * @return
	 */
	@RequestMapping("/viewMarker")
	public ModelAndView viewMarker(int id, String enclosureType, String strRoutePoints, HttpServletRequest request, HttpServletResponse response) throws Exception {
		double radius = 0;
		Map<String, Object> context = getRootMap();
		EnclosureConfig e = new EnclosureConfig();
		EnclosureConfig enclosureConfig = enclosureService.queryById(id);
		if (enclosureConfig != null) {
			e = enclosureConfig;
			if (Constants.MAP_BAIDU.equals(enclosureConfig.getMaptype())) {
				String points = "";
				String[] p = enclosureConfig.getPoints().split(";");
				for (int i = 0; i < p.length; i++) {

					PointLatLng pl = BaiduMapFixService.bd_decrypt(Double.valueOf(p[i].split(",")[1]), Double.valueOf(p[i].split(",")[0]));
					points += pl.getLng() + "," + pl.getLat() + ";";
				}
				enclosureConfig.setPoints(points.substring(0, points.length() - 1));
				PointLatLng pl1 = BaiduMapFixService.bd_decrypt(enclosureConfig.getCenterLat(), enclosureConfig.getCenterLng());
				enclosureConfig.setCenterLat(pl1.getLat());
				enclosureConfig.setCenterLng(pl1.getLng());
			}
		}
		if (!StringUtil.isEmptyWithNullStr(request.getParameter("radius"))) {
			radius = Double.valueOf(request.getParameter("radius"));
		}
		if (id == 0) {
			e.setRadius((new Double(radius)).intValue());
			e.setPoints(strRoutePoints);
			e.setEnclosureType(EnclosureConfig.MARKER);
		}
		context.put("enclosure", e);
		context.put("id", id);
		context.put("strRoutePoints", strRoutePoints);
		return forword("/area/editMarker", context);

	}


	@RequestMapping("/viewArea")
	public ModelAndView viewArea(int id, String enclosureType, String strRoutePoints, HttpServletRequest request, HttpServletResponse response) throws Exception {

		double radius = 0;
		Map<String, Object> context = getRootMap();
		EnclosureConfig e = new EnclosureConfig();
		EnclosureConfig enclosureConfig = enclosureService.queryById(id);
		if (enclosureConfig != null) {
			e = enclosureConfig;
		/*	Department department = departmentService.queryById(e.getDepId());
			if (department != null) {
				context.put("depName", department.getDepName());
			}*/
			context.put("startTime1", DateUtil.getPlusTime(e.getStartDate()));
			context.put("endTime1", DateUtil.getPlusTime(e.getEndDate()));
			if (Constants.MAP_BAIDU.equals(enclosureConfig.getMaptype())) {
				String points = "";
				String[] p = enclosureConfig.getPoints().split(";");
				for (int i = 0; i < p.length; i++) {

					PointLatLng pl = BaiduMapFixService.bd_decrypt(Double.valueOf(p[i].split(",")[1]), Double.valueOf(p[i].split(",")[0]));
					points += pl.getLng() + "," + pl.getLat() + ";";
				}
				enclosureConfig.setPoints(points.substring(0, points.length() - 1));
				PointLatLng pl1 = BaiduMapFixService.bd_decrypt(enclosureConfig.getCenterLat(), enclosureConfig.getCenterLng());
				enclosureConfig.setCenterLat(pl1.getLat());
				enclosureConfig.setCenterLng(pl1.getLng());
			}
		}
		if (!StringUtil.isEmptyWithNullStr(request.getParameter("radius"))) {
			radius = Double.valueOf(request.getParameter("radius"));
		}
		if (!StringUtil.isEmptyWithNullStr(enclosureType)) {
			String ecType = "";
			if ("circle".equals(enclosureType))
				ecType = EnclosureConfig.CIRCLE;
			else if ("rect".equals(enclosureType))
				ecType = EnclosureConfig.RECT;
			else if ("polygon".equals(enclosureType))
				ecType = EnclosureConfig.POLYGON;
			e.setEnclosureType(ecType);
		} else
			enclosureType = e.getEnclosureType();

		if (id == 0) {
			e.setRadius((new Double(radius)).intValue());
			e.setPoints(strRoutePoints);
			//e.setDepId(0);
		}

		context.put("enclosure", e);
		context.put("id", id);
		context.put("strRoutePoints", strRoutePoints);
		return forword("/area/editArea", context);


	}


	/**
	 * 添加或修改数据
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
	public void save(EnclosureConfig bean, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> context = new HashMap<String, Object>();
		User user = SessionUtils.getUser(request);
/*		if (bean.getDepId().intValue() == 0) {
			sendFailureMessage(response, "请选择所属分组!");
			return;
		}*/
		String startTime = "" + request.getParameter("startDateHidden");
		String endTime = "" + request.getParameter("endDateHidden");
		bean.setStartDate(DateUtil.getDateFromString(startTime));
		bean.setEndDate(DateUtil.getDateFromString(endTime));
		bean.setUserName(user.getLoginName());
		if (bean.getId().intValue() == 0) {
			bean.setMaptype(Constants.MAP_GOOGLE);
			PointLatLng pt = this.getPolygonCenter(bean.getPoints());
			bean.setCenterLat(pt.getLat());
			bean.setCenterLng(pt.getLng());
			bean.setId(null);
			bean.setCreateDate(new Date());
			enclosureService.add(bean);
		} else {
			PointLatLng pt = this.getPolygonCenter(bean.getPoints());
			bean.setCenterLat(pt.getLat());
			bean.setCenterLng(pt.getLng());
			bean.setMaptype(Constants.MAP_GOOGLE);
			enclosureService.updateBySelective(bean);
			EnclosureConfig enclosureConfig = enclosureService.queryById(bean.getId());
			bean = enclosureConfig;
		}
		context.put(SUCCESS, true);
		context.put("data", bean);
		HtmlUtil.writerJson(response, context);
	}

	@RequestMapping("/enclosureList")
	public void enclosureList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> context = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();

		User user = SessionUtils.getUser(request);
		if (user == null) {
			String path = request.getContextPath();
			response.sendRedirect(path + "/login");
		}
		List<Integer> depIds = getDepIds(user.getDepId());
		map.put("depIds", depIds);
		map.put("userName", user.getLoginName());
		List<EnclosureConfig> enclosureList = enclosureService.queryByMapList(map);
		for (EnclosureConfig enclosureConfig : enclosureList) {
			if (Constants.MAP_BAIDU.equals(enclosureConfig.getMaptype())) {
				String points = "";
				String[] p = enclosureConfig.getPoints().split(";");
				for (int i = 0; i < p.length; i++) {

					PointLatLng pl = BaiduMapFixService.bd_decrypt(Double.valueOf(p[i].split(",")[1]), Double.valueOf(p[i].split(",")[0]));
					points += pl.getLng() + "," + pl.getLat() + ";";
				}
				enclosureConfig.setPoints(points.substring(0, points.length() - 1));
				PointLatLng pl1 = BaiduMapFixService.bd_decrypt(enclosureConfig.getCenterLat(), enclosureConfig.getCenterLng());
				enclosureConfig.setCenterLat(pl1.getLat());
				enclosureConfig.setCenterLng(pl1.getLng());
			}
		}
		context.put(SUCCESS, true);
		context.put("data", enclosureList);
		HtmlUtil.writerJson(response, context);

	}


	@RequestMapping("/deleteAreas")
	public void deleteAreas(String enclosureIds, HttpServletRequest request, HttpServletResponse response) throws Exception {

		if (StringUtil.isEmptyWithNullStr(enclosureIds) == false) {
			String[] idarray = enclosureIds.split(",");
			for (String strEnclosureId : idarray) {
				EnclosureConfig enclosureConfig = new EnclosureConfig();
				enclosureConfig.setId(Integer.valueOf(strEnclosureId));
				enclosureConfig.setDeleted(1);
				enclosureService.deleteFake(enclosureConfig);
				sendSuccessMessage(response, "删除成功");
			}

		}

	}

	// 得到多边形的中心
	private PointLatLng getPolygonCenter(String strPoints) {
		List<PointLatLng> ls = getPoints(strPoints);
		if (ls.size() == 1)
			return ls.get(0);
		double maxLat = 0, maxLng = 0, minLat = 200, minLng = 200;

		for (PointLatLng pl : ls) {
			if (pl.getLat() > maxLat)
				maxLat = pl.getLat();

			if (pl.getLng() > maxLng)
				maxLng = pl.getLng();

			if (pl.getLat() < minLat)
				minLat = pl.getLat();

			if (pl.getLng() < minLng)
				minLng = pl.getLng();
		}

		double lat1 = minLat + (maxLat - minLat) / 2;
		double lng1 = minLng + (maxLng - minLng) / 2;

		return new PointLatLng(lat1, lng1);
	}

	private List<PointLatLng> getPoints(String strPoints) {
		List<PointLatLng> result = new ArrayList<PointLatLng>();

		String[] points = strPoints.split(";");
		for (String strPt : points) {
			if (StringUtil.isEmptyWithNullStr(strPt))
				continue;
			String[] pt = strPt.split(",");
			Double lng = Double.parseDouble(pt[0]);
			Double lat = Double.parseDouble(pt[1]);
			result.add(new PointLatLng(lat, lng));
		}
		return result;
	}
}
